package com.michaelli.androidmoneyrecord.db;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class FeeTypeDAO extends BaseDAO{

	public FeeTypeDAO(Context ctxt) {
		super(ctxt);
	}
	
	public String insertFeeType(String feeTypeName,String userId,boolean isInput){
			ContentValues values=new ContentValues();
			return String.valueOf(sdb.insert("feetype", "", values));
	}
	
	public void delFeeType(String feeTypeName,String userId){
		String feeTypeId=getFeeTypeIdByName(feeTypeName,userId);
		if(feeTypeId!=null){
			delFeeType(feeTypeId);
		}
	}
	
	public void delFeeType(String feeTypeId){
		sdb.delete("feetype", "_id= ? ", new String[]{feeTypeId});
	}
	
	public boolean reNameFeeType(String feeTypeName,String userId,String newFeeTypeName){
			String feeTypeId=getFeeTypeIdByName(feeTypeName,userId);
			if(feeTypeId==null){
				return false;
			}
		return reNameFeeType(feeTypeId, newFeeTypeName);
		
	}
	
	public boolean reNameFeeType(String feeTypeId,String newFeeTypeName){
		ContentValues values=new ContentValues();
		values.put("name", newFeeTypeName);
		int effecedNum=sdb.update("feetype", values, "_id=?", new String[]{feeTypeId});
		if(effecedNum>0){
			return true;
		}
		return false;
	}
	
	public ArrayList<HashMap<String, String>> getFeeType(boolean isInput,String userId){
		Cursor c=sdb.query("feetype", null, "isInput = ? AND user_id= ? ", new String[]{isInput?"1":"0",userId}, null, null, null);
		ArrayList<HashMap<String, String>> feeTypeList=new ArrayList<HashMap<String,String>>();
		while(c.moveToNext()){
			HashMap<String, String> feeType=new HashMap<String, String>();
			feeType.put("id", c.getString(c.getColumnIndex("_id")));
			feeType.put("name",  c.getString(c.getColumnIndex("name")));
			feeType.put("user_id",  c.getString(c.getColumnIndex("user_id")));
			feeType.put("isInput",  c.getString(c.getColumnIndex("isInput")));
			feeTypeList.add(feeType);
		}
		c.close();
		return feeTypeList;
	}
	
	public String getFeeTypeNameById(String feeTypeId){
		String feeTypeName=null;
		Cursor c=sdb.query("feetype", new String[]{"name"}, "_id= ? ", new String[]{feeTypeId}, null, null, null);
		if(c.moveToNext()){
			feeTypeName=c.getString(0);
		}
		return feeTypeName;
	}
	
	public String getFeeTypeIdByName(String feeTypeName,String userId){
		String feeTypeId=null;
		Cursor c=sdb.query("feetype", new String[]{"_id"}, "name = ? AND user_id= ? ", new String[]{feeTypeName,userId}, null, null, null);
		if(c.moveToNext()){
			feeTypeId=c.getString(0);
		}
		return feeTypeId;
		
	}
	
	
}
